<template>
  <div class="settings-page">
    <!-- 设置头部 -->
    <div class="settings-header">
      <div class="header-info">
        <h2 class="settings-title">
          <Icon name="settings" :size="24" />
          设置
        </h2>
        <p class="settings-description">管理您的应用偏好和配置</p>
      </div>

      <div class="header-actions">
        <Button type="secondary" icon="refresh-cw" @click="resetToDefaults">
          重置默认
        </Button>

        <Button
          type="primary"
          icon="save"
          @click="saveSettings"
          :loading="saving"
        >
          保存设置
        </Button>
      </div>
    </div>

    <!-- 设置内容 -->
    <div class="settings-content">
      <!-- 侧边栏导航 -->
      <div class="settings-sidebar">
        <nav class="settings-nav">
          <div
            v-for="category in settingsCategories"
            :key="category.key"
            class="nav-item"
            :class="{ active: activeCategory === category.key }"
            @click="activeCategory = category.key"
          >
            <Icon :name="category.icon" :size="16" />
            <span class="nav-text">{{ category.title }}</span>
            <Icon
              v-if="hasUnsavedChanges(category.key)"
              name="circle"
              :size="6"
              class="unsaved-indicator"
            />
          </div>
        </nav>
      </div>

      <!-- 设置面板 -->
      <div class="settings-panel">
        <!-- 通用设置 -->
        <div v-if="activeCategory === 'general'" class="settings-section">
          <div class="section-header">
            <h3 class="section-title">通用设置</h3>
            <p class="section-description">配置应用的基本行为和外观</p>
          </div>

          <div class="settings-groups">
            <!-- 语言设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">语言和地区</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">界面语言</label>
                  <p class="setting-description">选择应用界面显示的语言</p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.general.language"
                    class="setting-select"
                  >
                    <option value="zh-CN">简体中文</option>
                    <option value="zh-TW">繁体中文</option>
                    <option value="en-US">English</option>
                    <option value="ja-JP">日本語</option>
                  </select>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">时区</label>
                  <p class="setting-description">设置时间显示的时区</p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.general.timezone"
                    class="setting-select"
                  >
                    <option value="Asia/Shanghai">北京时间 (UTC+8)</option>
                    <option value="Asia/Tokyo">东京时间 (UTC+9)</option>
                    <option value="America/New_York">纽约时间 (UTC-5)</option>
                    <option value="Europe/London">伦敦时间 (UTC+0)</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 主题设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">外观主题</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">主题模式</label>
                  <p class="setting-description">选择应用的外观主题</p>
                </div>
                <div class="setting-control">
                  <div class="theme-selector">
                    <div
                      v-for="theme in themeOptions"
                      :key="theme.value"
                      class="theme-option"
                      :class="{
                        active: settings.general.theme === theme.value,
                      }"
                      @click="settings.general.theme = theme.value"
                    >
                      <div
                        class="theme-preview"
                        :class="`theme-${theme.value}`"
                      >
                        <div class="preview-header"></div>
                        <div class="preview-content">
                          <div class="preview-sidebar"></div>
                          <div class="preview-main"></div>
                        </div>
                      </div>
                      <span class="theme-name">{{ theme.label }}</span>
                    </div>
                  </div>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">主题色</label>
                  <p class="setting-description">自定义应用的主色调</p>
                </div>
                <div class="setting-control">
                  <div class="color-picker">
                    <div
                      v-for="color in colorOptions"
                      :key="color.value"
                      class="color-option"
                      :class="{
                        active: settings.general.primaryColor === color.value,
                      }"
                      :style="{ backgroundColor: color.value }"
                      @click="settings.general.primaryColor = color.value"
                    >
                      <Icon
                        v-if="settings.general.primaryColor === color.value"
                        name="check"
                        :size="12"
                      />
                    </div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 启动设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">启动行为</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">开机自启动</label>
                  <p class="setting-description">系统启动时自动运行应用</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.general.autoStart"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">最小化到系统托盘</label>
                  <p class="setting-description">
                    关闭窗口时最小化到系统托盘而不是退出
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.general.minimizeToTray"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 聊天设置 -->
        <div v-if="activeCategory === 'chat'" class="settings-section">
          <div class="section-header">
            <h3 class="section-title">聊天设置</h3>
            <p class="section-description">配置聊天功能的行为和偏好</p>
          </div>

          <div class="settings-groups">
            <!-- 消息设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">消息显示</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">消息气泡样式</label>
                  <p class="setting-description">选择聊天消息的显示样式</p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.chat.messageStyle"
                    class="setting-select"
                  >
                    <option value="bubble">气泡样式</option>
                    <option value="card">卡片样式</option>
                    <option value="minimal">简约样式</option>
                  </select>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">显示时间戳</label>
                  <p class="setting-description">在消息旁显示发送时间</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.showTimestamp"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">显示头像</label>
                  <p class="setting-description">在消息旁显示用户和AI头像</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.showAvatar"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 输入设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">输入行为</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">发送快捷键</label>
                  <p class="setting-description">选择发送消息的快捷键</p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.chat.sendShortcut"
                    class="setting-select"
                  >
                    <option value="enter">Enter</option>
                    <option value="ctrl-enter">Ctrl + Enter</option>
                    <option value="shift-enter">Shift + Enter</option>
                  </select>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">自动保存草稿</label>
                  <p class="setting-description">自动保存未发送的消息内容</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.autoSaveDraft"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">启用表情符号</label>
                  <p class="setting-description">
                    在输入框中显示表情符号选择器
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.enableEmoji"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 通知设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">消息通知</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">桌面通知</label>
                  <p class="setting-description">收到新消息时显示桌面通知</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.desktopNotification"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">声音提醒</label>
                  <p class="setting-description">收到新消息时播放提示音</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.chat.soundNotification"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 人格设置 -->
        <div v-if="activeCategory === 'persona'" class="settings-section">
          <div class="section-header">
            <h3 class="section-title">人格设置</h3>
            <p class="section-description">管理AI人格的行为和特性</p>
          </div>

          <div class="settings-groups">
            <!-- 默认人格 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">默认人格</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">启动时的默认人格</label>
                  <p class="setting-description">应用启动时自动激活的人格</p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.persona.defaultPersona"
                    class="setting-select"
                  >
                    <option value="">无默认人格</option>
                    <option value="sakura">小樱</option>
                    <option value="doctor">医生助手</option>
                    <option value="chef">料理专家</option>
                    <option value="companion">情感陪伴</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 人格切换 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">人格切换</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">切换冷却时间</label>
                  <p class="setting-description">
                    两次人格切换之间的最小间隔（秒）
                  </p>
                </div>
                <div class="setting-control">
                  <Input
                    v-model.number="settings.persona.switchCooldown"
                    type="number"
                    min="0"
                    max="300"
                    suffix="秒"
                  />
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">记住上次人格</label>
                  <p class="setting-description">
                    重新启动时恢复上次使用的人格
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.persona.rememberLastPersona"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 人格行为 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">人格行为</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">自动适应语境</label>
                  <p class="setting-description">
                    根据对话内容自动调整人格表现
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.persona.autoAdapt"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">情感表达强度</label>
                  <p class="setting-description">调整人格情感表达的强烈程度</p>
                </div>
                <div class="setting-control">
                  <div class="slider-control">
                    <input
                      v-model.number="settings.persona.emotionIntensity"
                      type="range"
                      min="0"
                      max="100"
                      class="setting-slider"
                    />
                    <span class="slider-value"
                      >{{ settings.persona.emotionIntensity }}%</span
                    >
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 隐私设置 -->
        <div v-if="activeCategory === 'privacy'" class="settings-section">
          <div class="section-header">
            <h3 class="section-title">隐私设置</h3>
            <p class="section-description">管理数据隐私和安全设置</p>
          </div>

          <div class="settings-groups">
            <!-- 数据收集 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">数据收集</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">使用统计</label>
                  <p class="setting-description">
                    允许收集匿名使用统计以改进产品
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.privacy.analytics"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">错误报告</label>
                  <p class="setting-description">
                    自动发送错误报告以帮助修复问题
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.privacy.errorReporting"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>

            <!-- 数据存储 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">数据存储</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">本地数据加密</label>
                  <p class="setting-description">
                    加密存储在本地的聊天记录和设置
                  </p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.privacy.encryptLocalData"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">聊天记录保留时间</label>
                  <p class="setting-description">
                    自动删除超过指定时间的聊天记录
                  </p>
                </div>
                <div class="setting-control">
                  <select
                    v-model="settings.privacy.chatRetention"
                    class="setting-select"
                  >
                    <option value="forever">永久保留</option>
                    <option value="1year">1年</option>
                    <option value="6months">6个月</option>
                    <option value="3months">3个月</option>
                    <option value="1month">1个月</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 数据管理 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">数据管理</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">导出数据</label>
                  <p class="setting-description">导出您的聊天记录和设置数据</p>
                </div>
                <div class="setting-control">
                  <Button type="secondary" icon="download" @click="exportData">
                    导出数据
                  </Button>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">清除所有数据</label>
                  <p class="setting-description">
                    删除所有本地存储的数据，此操作不可撤销
                  </p>
                </div>
                <div class="setting-control">
                  <Button type="danger" icon="trash" @click="clearAllData">
                    清除数据
                  </Button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 高级设置 -->
        <div v-if="activeCategory === 'advanced'" class="settings-section">
          <div class="section-header">
            <h3 class="section-title">高级设置</h3>
            <p class="section-description">面向高级用户的配置选项</p>
          </div>

          <div class="settings-groups">
            <!-- 性能设置 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">性能优化</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">硬件加速</label>
                  <p class="setting-description">启用GPU硬件加速以提升性能</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.advanced.hardwareAcceleration"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">内存限制</label>
                  <p class="setting-description">
                    设置应用最大内存使用量（MB）
                  </p>
                </div>
                <div class="setting-control">
                  <Input
                    v-model.number="settings.advanced.memoryLimit"
                    type="number"
                    min="512"
                    max="8192"
                    suffix="MB"
                  />
                </div>
              </div>
            </div>

            <!-- 开发者选项 -->
            <div class="setting-group">
              <div class="group-header">
                <h4 class="group-title">开发者选项</h4>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">调试模式</label>
                  <p class="setting-description">启用调试模式以查看详细日志</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.advanced.debugMode"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>

              <div class="setting-item">
                <div class="setting-info">
                  <label class="setting-label">开发者工具</label>
                  <p class="setting-description">启用开发者工具快捷键</p>
                </div>
                <div class="setting-control">
                  <label class="toggle-switch">
                    <input
                      v-model="settings.advanced.devTools"
                      type="checkbox"
                      class="toggle-input"
                    />
                    <span class="toggle-slider"></span>
                  </label>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 保存状态提示 -->
    <div v-if="showSaveStatus" class="save-status" :class="saveStatusType">
      <Icon :name="saveStatusIcon" :size="16" />
      <span>{{ saveStatusMessage }}</span>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { useSettingsStore } from "@/stores/settings";
import Icon from "@/components/common/Icon.vue";
import Button from "@/components/common/Button.vue";
import Input from "@/components/common/Input.vue";

interface Settings {
  general: {
    language: string;
    timezone: string;
    theme: string;
    primaryColor: string;
    autoStart: boolean;
    minimizeToTray: boolean;
  };
  chat: {
    messageStyle: string;
    showTimestamp: boolean;
    showAvatar: boolean;
    sendShortcut: string;
    autoSaveDraft: boolean;
    enableEmoji: boolean;
    desktopNotification: boolean;
    soundNotification: boolean;
  };
  persona: {
    defaultPersona: string;
    switchCooldown: number;
    rememberLastPersona: boolean;
    autoAdapt: boolean;
    emotionIntensity: number;
  };
  privacy: {
    analytics: boolean;
    errorReporting: boolean;
    encryptLocalData: boolean;
    chatRetention: string;
  };
  advanced: {
    hardwareAcceleration: boolean;
    memoryLimit: number;
    debugMode: boolean;
    devTools: boolean;
  };
}

// Store
const settingsStore = useSettingsStore();

// 响应式数据
const activeCategory = ref("general");
const saving = ref(false);
const showSaveStatus = ref(false);
const saveStatusType = ref<"success" | "error">("success");
const saveStatusMessage = ref("");

// 设置数据
const settings = ref<Settings>({
  general: {
    language: "zh-CN",
    timezone: "Asia/Shanghai",
    theme: "auto",
    primaryColor: "#3b82f6",
    autoStart: false,
    minimizeToTray: true,
  },
  chat: {
    messageStyle: "bubble",
    showTimestamp: true,
    showAvatar: true,
    sendShortcut: "enter",
    autoSaveDraft: true,
    enableEmoji: true,
    desktopNotification: true,
    soundNotification: false,
  },
  persona: {
    defaultPersona: "",
    switchCooldown: 30,
    rememberLastPersona: true,
    autoAdapt: true,
    emotionIntensity: 70,
  },
  privacy: {
    analytics: false,
    errorReporting: true,
    encryptLocalData: true,
    chatRetention: "1year",
  },
  advanced: {
    hardwareAcceleration: true,
    memoryLimit: 2048,
    debugMode: false,
    devTools: false,
  },
});

// 原始设置（用于检测更改）
const originalSettings = ref<Settings>(
  JSON.parse(JSON.stringify(settings.value)),
);

// 设置分类
const settingsCategories = [
  { key: "general", title: "通用", icon: "settings" },
  { key: "chat", title: "聊天", icon: "message-circle" },
  { key: "persona", title: "人格", icon: "user" },
  { key: "privacy", title: "隐私", icon: "shield" },
  { key: "advanced", title: "高级", icon: "code" },
];

// 主题选项
const themeOptions = [
  { value: "light", label: "浅色" },
  { value: "dark", label: "深色" },
  { value: "auto", label: "自动" },
];

// 颜色选项
const colorOptions = [
  { value: "#3b82f6", label: "蓝色" },
  { value: "#10b981", label: "绿色" },
  { value: "#f59e0b", label: "橙色" },
  { value: "#ef4444", label: "红色" },
  { value: "#8b5cf6", label: "紫色" },
  { value: "#06b6d4", label: "青色" },
];

// 计算属性
const saveStatusIcon = computed(() => {
  return saveStatusType.value === "success" ? "check" : "x";
});

// 方法
const hasUnsavedChanges = (category: string): boolean => {
  return (
    JSON.stringify(settings.value[category as keyof Settings]) !==
    JSON.stringify(originalSettings.value[category as keyof Settings])
  );
};

const saveSettings = async () => {
  saving.value = true;
  try {
    await settingsStore.saveSettings(settings.value);
    originalSettings.value = JSON.parse(JSON.stringify(settings.value));
    showSaveStatusMessage("设置保存成功", "success");
  } catch (error) {
    console.error("保存设置失败:", error);
    showSaveStatusMessage("设置保存失败", "error");
  } finally {
    saving.value = false;
  }
};

const resetToDefaults = () => {
  if (confirm("确定要重置所有设置到默认值吗？此操作不可撤销。")) {
    settings.value = {
      general: {
        language: "zh-CN",
        timezone: "Asia/Shanghai",
        theme: "auto",
        primaryColor: "#3b82f6",
        autoStart: false,
        minimizeToTray: true,
      },
      chat: {
        messageStyle: "bubble",
        showTimestamp: true,
        showAvatar: true,
        sendShortcut: "enter",
        autoSaveDraft: true,
        enableEmoji: true,
        desktopNotification: true,
        soundNotification: false,
      },
      persona: {
        defaultPersona: "",
        switchCooldown: 30,
        rememberLastPersona: true,
        autoAdapt: true,
        emotionIntensity: 70,
      },
      privacy: {
        analytics: false,
        errorReporting: true,
        encryptLocalData: true,
        chatRetention: "1year",
      },
      advanced: {
        hardwareAcceleration: true,
        memoryLimit: 2048,
        debugMode: false,
        devTools: false,
      },
    };
  }
};

const exportData = () => {
  const data = {
    settings: settings.value,
    exportTime: new Date().toISOString(),
  };

  const blob = new Blob([JSON.stringify(data, null, 2)], {
    type: "application/json",
  });
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = `cardcaptor-sakura-settings-${new Date().toISOString().split("T")[0]}.json`;
  document.body.appendChild(a);
  a.click();
  document.body.removeChild(a);
  URL.revokeObjectURL(url);
};

const clearAllData = () => {
  if (
    confirm(
      "确定要清除所有数据吗？这将删除所有聊天记录、设置和用户数据，此操作不可撤销。",
    )
  ) {
    if (confirm("请再次确认：您真的要删除所有数据吗？")) {
      // 清除数据的逻辑
      localStorage.clear();
      sessionStorage.clear();
      showSaveStatusMessage("所有数据已清除", "success");

      // 重新加载页面
      setTimeout(() => {
        window.location.reload();
      }, 2000);
    }
  }
};

const showSaveStatusMessage = (message: string, type: "success" | "error") => {
  saveStatusMessage.value = message;
  saveStatusType.value = type;
  showSaveStatus.value = true;

  setTimeout(() => {
    showSaveStatus.value = false;
  }, 3000);
};

// 监听器
watch(
  settings,
  () => {
    // 自动保存某些设置
    if (settings.value.general.theme !== originalSettings.value.general.theme) {
      document.documentElement.setAttribute(
        "data-theme",
        settings.value.general.theme,
      );
    }

    if (
      settings.value.general.primaryColor !==
      originalSettings.value.general.primaryColor
    ) {
      document.documentElement.style.setProperty(
        "--primary-color",
        settings.value.general.primaryColor,
      );
    }
  },
  { deep: true },
);

// 生命周期
onMounted(async () => {
  try {
    const savedSettings = await settingsStore.loadSettings();
    if (savedSettings) {
      settings.value = { ...settings.value, ...savedSettings };
      originalSettings.value = JSON.parse(JSON.stringify(settings.value));
    }
  } catch (error) {
    console.error("加载设置失败:", error);
  }
});
</script>

<style scoped>
/* 设置页面基础样式 */
.settings-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--bg-primary);
  overflow: hidden;
}

/* 设置头部 */
.settings-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 24px 32px;
  border-bottom: 1px solid var(--border-color);
  background-color: var(--bg-secondary);
}

.header-info {
  flex: 1;
}

.settings-title {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 24px;
  font-weight: 700;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.settings-description {
  font-size: 16px;
  color: var(--text-secondary);
  margin: 0;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 设置内容 */
.settings-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 侧边栏 */
.settings-sidebar {
  width: 240px;
  background-color: var(--bg-secondary);
  border-right: 1px solid var(--border-color);
  overflow-y: auto;
}

.settings-nav {
  padding: 16px 0;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s ease;
  position: relative;
}

.nav-item:hover {
  background-color: var(--bg-tertiary);
}

.nav-item.active {
  background-color: var(--primary-color-light);
  color: var(--primary-color);
  border-right: 3px solid var(--primary-color);
}

.nav-text {
  font-size: 14px;
  font-weight: 500;
  flex: 1;
}

.unsaved-indicator {
  color: var(--warning-color);
}

/* 设置面板 */
.settings-panel {
  flex: 1;
  overflow-y: auto;
  padding: 32px;
}

.settings-section {
  max-width: 800px;
}

.section-header {
  margin-bottom: 32px;
}

.section-title {
  font-size: 20px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0 0 8px;
}

.section-description {
  font-size: 14px;
  color: var(--text-secondary);
  margin: 0;
}

/* 设置组 */
.settings-groups {
  display: flex;
  flex-direction: column;
  gap: 32px;
}

.setting-group {
  background-color: var(--bg-secondary);
  border-radius: 12px;
  padding: 24px;
  border: 1px solid var(--border-color);
}

.group-header {
  margin-bottom: 20px;
}

.group-title {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
  margin: 0;
}

/* 设置项 */
.setting-item {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 24px;
  padding: 16px 0;
  border-bottom: 1px solid var(--border-color);
}

.setting-item:last-child {
  border-bottom: none;
}

.setting-info {
  flex: 1;
}

.setting-label {
  font-size: 14px;
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 4px;
  display: block;
}

.setting-description {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.4;
  margin: 0;
}

.setting-control {
  flex-shrink: 0;
}

/* 表单控件 */
.setting-select {
  padding: 6px 12px;
  border: 1px solid var(--border-color);
  border-radius: 6px;
  background-color: var(--bg-primary);
  color: var(--text-primary);
  font-size: 14px;
  min-width: 150px;
}

.setting-select:focus {
  outline: none;
  border-color: var(--primary-color);
}

/* 开关控件 */
.toggle-switch {
  position: relative;
  display: inline-block;
  width: 44px;
  height: 24px;
  cursor: pointer;
}

.toggle-input {
  opacity: 0;
  width: 0;
  height: 0;
}

.toggle-slider {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: var(--bg-tertiary);
  border-radius: 24px;
  transition: 0.3s;
  border: 1px solid var(--border-color);
}

.toggle-slider:before {
  position: absolute;
  content: "";
  height: 18px;
  width: 18px;
  left: 2px;
  bottom: 2px;
  background-color: var(--text-primary);
  border-radius: 50%;
  transition: 0.3s;
}

.toggle-input:checked + .toggle-slider {
  background-color: var(--primary-color);
  border-color: var(--primary-color);
}

.toggle-input:checked + .toggle-slider:before {
  transform: translateX(20px);
  background-color: white;
}

/* 滑块控件 */
.slider-control {
  display: flex;
  align-items: center;
  gap: 12px;
  min-width: 200px;
}

.setting-slider {
  flex: 1;
  height: 4px;
  border-radius: 2px;
  background: var(--bg-tertiary);
  outline: none;
  -webkit-appearance: none;
}

.setting-slider::-webkit-slider-thumb {
  -webkit-appearance: none;
  appearance: none;
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
}

.setting-slider::-moz-range-thumb {
  width: 16px;
  height: 16px;
  border-radius: 50%;
  background: var(--primary-color);
  cursor: pointer;
  border: none;
}

.slider-value {
  font-size: 12px;
  color: var(--text-secondary);
  min-width: 40px;
  text-align: right;
}

/* 主题选择器 */
.theme-selector {
  display: flex;
  gap: 12px;
}

.theme-option {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  padding: 8px;
  border-radius: 8px;
  transition: all 0.2s ease;
}

.theme-option:hover {
  background-color: var(--bg-tertiary);
}

.theme-option.active {
  background-color: var(--primary-color-light);
}

.theme-preview {
  width: 60px;
  height: 40px;
  border-radius: 6px;
  border: 1px solid var(--border-color);
  overflow: hidden;
  display: flex;
  flex-direction: column;
}

.theme-light {
  background-color: #ffffff;
}

.theme-dark {
  background-color: #1a1a1a;
}

.theme-auto {
  background: linear-gradient(90deg, #ffffff 50%, #1a1a1a 50%);
}

.preview-header {
  height: 8px;
  background-color: var(--bg-tertiary);
}

.preview-content {
  flex: 1;
  display: flex;
}

.preview-sidebar {
  width: 20px;
  background-color: var(--bg-secondary);
}

.preview-main {
  flex: 1;
  background-color: var(--bg-primary);
}

.theme-name {
  font-size: 12px;
  color: var(--text-secondary);
}

/* 颜色选择器 */
.color-picker {
  display: flex;
  gap: 8px;
}

.color-option {
  width: 32px;
  height: 32px;
  border-radius: 6px;
  cursor: pointer;
  border: 2px solid transparent;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.2s ease;
}

.color-option:hover {
  transform: scale(1.1);
}

.color-option.active {
  border-color: var(--text-primary);
  box-shadow: 0 0 0 2px var(--bg-primary);
}

.color-option .icon {
  color: white;
  filter: drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3));
}

/* 保存状态 */
.save-status {
  position: fixed;
  bottom: 24px;
  right: 24px;
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: var(--shadow-lg);
  z-index: 1000;
  animation: slideIn 0.3s ease;
}

.save-status.success {
  background-color: var(--success-color);
  color: white;
}

.save-status.error {
  background-color: var(--error-color);
  color: white;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 响应式 */
@media (max-width: 1024px) {
  .settings-content {
    flex-direction: column;
  }

  .settings-sidebar {
    width: 100%;
    height: auto;
    border-right: none;
    border-bottom: 1px solid var(--border-color);
  }

  .settings-nav {
    display: flex;
    overflow-x: auto;
    padding: 8px 16px;
  }

  .nav-item {
    flex-shrink: 0;
    white-space: nowrap;
    border-right: none;
    border-bottom: 3px solid transparent;
  }

  .nav-item.active {
    border-right: none;
    border-bottom-color: var(--primary-color);
  }
}

@media (max-width: 768px) {
  .settings-header {
    flex-direction: column;
    gap: 16px;
    align-items: stretch;
    padding: 16px 20px;
  }

  .header-actions {
    justify-content: flex-end;
  }

  .settings-panel {
    padding: 20px;
  }

  .setting-item {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .theme-selector {
    justify-content: center;
  }

  .color-picker {
    justify-content: center;
  }
}

@media (max-width: 480px) {
  .settings-header {
    padding: 12px 16px;
  }

  .settings-panel {
    padding: 16px;
  }

  .setting-group {
    padding: 16px;
  }

  .settings-title {
    font-size: 20px;
  }

  .section-title {
    font-size: 18px;
  }
}

/* 滚动条样式 */
.settings-sidebar::-webkit-scrollbar,
.settings-panel::-webkit-scrollbar {
  width: 6px;
}

.settings-sidebar::-webkit-scrollbar-track,
.settings-panel::-webkit-scrollbar-track {
  background: var(--bg-tertiary);
  border-radius: 3px;
}

.settings-sidebar::-webkit-scrollbar-thumb,
.settings-panel::-webkit-scrollbar-thumb {
  background: var(--text-tertiary);
  border-radius: 3px;
}

.settings-sidebar::-webkit-scrollbar-thumb:hover,
.settings-panel::-webkit-scrollbar-thumb:hover {
  background: var(--text-secondary);
}
</style>
